package com.jeaven.rtda.heap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// JVM 的堆内存
public class Heap {
    private static final Map<String, KClass> STRING_K_CLASS_MAP;
    private static final Map<String, NativeMethod> STRING_NATIVE_METHOD_MAP;

    static {
        STRING_K_CLASS_MAP = new HashMap<>();
        STRING_NATIVE_METHOD_MAP = new HashMap<>();
    }

    public Heap() {
        super();
    }

    public KClass findClass(String key) {
        return STRING_K_CLASS_MAP.get(key);
    }

    public NativeMethod findNativeMethod(String key) {
        return STRING_NATIVE_METHOD_MAP.get(key);
    }

    public void registerClass(String key, KClass kClass) {
//        if (EnvHolder.verboseClass) {
//            String source = clazz.classLoader.getName();
//            if (clazz.classFile != null && clazz.classFile.getSource() != null) {
//                source = clazz.classFile.getSource();
//            }
//            Logger.clazz("[Loaded " + name + " from " + source + "]");
//        }
        if(STRING_K_CLASS_MAP.containsKey(key)) {
            throw new IllegalStateException("类 " + kClass.name + " 已经注册过了");
        }
        STRING_K_CLASS_MAP.put(key, kClass);
    }

    public void registerNativeMethod(String key, NativeMethod nativeMethod) {
        if(STRING_NATIVE_METHOD_MAP.containsKey(key)) {
            throw new IllegalStateException("本地方法 " + nativeMethod.debug("") + " 已经注册过了");
        }
        STRING_NATIVE_METHOD_MAP.put(key, nativeMethod);
    }

    public List<KClass> getClasses() {
        return new ArrayList<>(STRING_K_CLASS_MAP.values());
    }

    public static void registerMethod(String methodName, NativeMethod nativeMethod) {
        if(STRING_NATIVE_METHOD_MAP.containsKey(methodName)) {
            throw new IllegalStateException();
        }
        STRING_NATIVE_METHOD_MAP.put(methodName, nativeMethod);
    }
}
